package com.ubivelox.uienginesample_20100726_002;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;
import android.os.SystemClock;
import android.util.Log;


public class PlaneRenderer implements Renderer {
	
	private Context mContext;
	private Plane mPlane;
	private float mCubeRotAngle = 0;
	private int[] mTextures = new int[1];	
//	private Bitmap mBitmap;
	private TextureLoader mLoader;

	private int mFrames = 1;
	private long mStartTime;
	private final int SAMPLE_PERIOD_FRAMES = 10;
	private float mMsPerFrame;
	private float mPrevMsPerFrame;
	private final float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES;
	
	public PlaneRenderer(Context context, TextureLoader loader) {		
		mPlane = new Plane();     
		mContext = context;		
		mLoader = loader;
	}
	
	public interface TextureLoader{
		void loadTexture(GL10 gl, int[] textures);
	}
	
	@Override
	public void onDrawFrame(GL10 gl) {
		// Clears the screen and depth buffer.
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
                GL10.GL_MODULATE);				
		
		gl.glLoadIdentity(); 				

		GLU.gluLookAt(gl, 0, 0, 7, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
		
		mLoader.loadTexture(gl, mTextures);
				
		gl.glPushMatrix();				
		gl.glRotatef(mCubeRotAngle, 0.0f, 0.0f, 1.0f);
		mPlane.draw(gl);
		gl.glPopMatrix();

		mCubeRotAngle += 5;		
		checkMsPF();
	}

	private void checkMsPF() {
	    long time = SystemClock.uptimeMillis();
	    if(mStartTime == 0)
	        mStartTime = time;
	    
	    if(mFrames++ == SAMPLE_PERIOD_FRAMES){
	        mFrames = 1;
	        long delta = time - mStartTime;
	        mStartTime = time;
	        mMsPerFrame = delta * SAMPLE_FACTOR;	        
	    }
	    
	    if(mPrevMsPerFrame != mMsPerFrame){
	        mPrevMsPerFrame = mMsPerFrame;
	        Log.d("==== fps ====", String.valueOf(1000/mMsPerFrame));
	    }
	    
    }

    @Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
				100.0f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();

	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
	    
        gl.glGenTextures(1, mTextures, 0);       
		        
		gl.glClearColor(0.3f, 0.3f, 0.3f, 0.0f);
		gl.glShadeModel(GL10.GL_SMOOTH);
		
		gl.glEnable(GL10.GL_TEXTURE_2D);		
			
		gl.glClearDepthf(1.0f);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);						
                      
	}

}
